<?php

namespace app\admin\controller\yalimedia;

use app\common\controller\Backend;

use app\common\model\CourseQuestionCategory as CourseQuestionCategoryModel;
use think\Cache;
use think\Db;
use fast\Tree;

/**
 * 课程题库列表
 *
 * @icon fa fa-circle-o
 */
class Coursequestioncategory extends Backend
{

    protected $model = null;
    protected $modelCate = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new  CourseQuestionCategoryModel;
        
    }

    
    /**
     * 查看
     */
    public function index()
    {
        $ids = input('ids');

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = $this->model
                // ->with('question')
                ->where($where)
                ->where(['content_id'=>$ids])
                ->order($sort,$order)
                ->paginate(99999);


            $tree = Tree::instance();
            $tree->init($list->toArray()['data'], 'pid');
            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');


            $result = array("total" =>count($list), "rows" => $list);
            return json($result);
        }
        $this->assign('course_id',input('course_id'));
        $this->assign('ids',$ids);
        return $this->view->fetch();
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        $ids = input('ids');
        $this->assign('ids',$ids);

        if (false === $this->request->isPost()) {

            $parentList = $this->model->where(['pid'=>0,'content_id'=>$ids])->column('name','id');
            $this->view->assign("parentList", $parentList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }



    /**
     * 编辑
     */
    public function edit($ids = null)
    {
       
        $row = $this->model->get($ids);
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            
            if ($params) {
                $params = $this->preExcludeFields($params);
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $parentList = $this->model->where(['pid'=>0,'content_id'=>$row->content_id])->column('name','id');
        $this->view->assign("parentList", $parentList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
     
        $this->model->where('id','IN',$ids)->delete();
        $this->success();
    }



     /**
     * 目录排序
     */
    public function sort(){
        if ($this->request->isAjax()) {
            $params = $this->request->post("row/a");

            $row = $this->model->where(['id'=>$params['id'],'content_id' => $params['content_id']])->find();
            if(empty($row)){
                $this->error("当前记录不存在");
            }
            $weigh      = $row['weigh'];
            $new_weigh  = $params['weigh'];
            $content_id = $row['content_id']; 

            $total = $this->model->where(['content_id'=>$content_id])->count();
            if($new_weigh<=0){
                $new_weigh = 1;
            }else if($new_weigh >= $total){
                $new_weigh = $total;
            }
    
            $this->model->where(['content_id'=>$content_id,'weigh'=>$new_weigh])->update(['weigh'=>$weigh]);
            $this->model->where(['content_id'=>$content_id,'id'=>$row['id']])->update(['weigh'=>$new_weigh]);
            $this->success("请求成功");
        }

        $id = $this->request->param('ids');
        $row = $this->model->where(['id'=>$id])->find();
        $this->assign('row',$row);
        return $this->view->fetch();
    }
}
